<template>
  <a-drawer
    title="新建角色"
    :open="open"
    :maskClosable="false"
    :width="634"
    @close="onCancel"
  >
    <!-- footer -->
    <template #footer>
      <a-space class="j-r-flex">
        <a-button @click="onCancel">取 消</a-button>
        <a-button type="primary" :loading="loading" @click="submitForm">
          确 认
        </a-button>
      </a-space>
    </template>

    <!-- loading -->
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <!-- form -->
    <div class="float-left mt-24" v-show="!init">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        autocomplete="off"
      >
        <a-form-item label="角色名称" name="name">
          <a-input
            v-model:value="formState.name"
            style="width: 424px"
            placeholder="请在此处输入角色名称"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="操作权限" name="action_ids">
          <a-tree-select
            v-model:value="formState.action_ids"
            :tree-data="actions"
            tree-checkable
            multiple
            allow-clear
            listHeight="600"
            style="width: 424px"
            placeholder="请选择权限"
          />
        </a-form-item>

        <a-form-item label="数据权限" name="permission_ids">
          <a-tree-select
            v-model:value="formState.permission_ids"
            :tree-data="permissions"
            tree-checkable
            multiple
            allow-clear
            listHeight="600"
            style="width: 424px"
            placeholder="请选择权限"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { message } from "ant-design-vue";
import { adminRole } from "@/api";

interface Props {
  open: boolean;
  onCancel: () => void;
}
const props = defineProps<Props>();

// 表单引用
const formRef = ref();

// 加载状态
const init = ref(true);
const loading = ref(false);

// 权限数据
const permissions = ref<any[]>([]);
const actions = ref<any[]>([]);

// 表单数据
const formState = ref({
  name: "",
  permission_ids: [] as number[],
  action_ids: [] as number[],
});

// 校验规则
const rules = {
  name: [{ required: true, message: "请输入角色名称!" }],
};

// 监听抽屉开启，初始化数据
watch(
  () => props.open,
  (val) => {
    if (val) {
      init.value = true;
      loadParams();
      // 重置表单
      formState.value = {
        name: "",
        permission_ids: [],
        action_ids: [],
      };
    }
  }
);

// 加载参数
const loadParams = () => {
  adminRole.createAdminRole().then((res: any) => {
    const arr: any[] = [];
    const arr2: any[] = [];
    const actionsData = res.data.perm_action.action;
    const permissionsData = res.data.perm_action.data;

    // 数据权限
    for (const item of permissionsData) {
      const group = arr.find((it) => it.title === item.group_name);
      if (group) {
        group.children.push({ title: item.name, value: item.id });
      } else {
        arr.push({
          title: item.group_name,
          value: item.group_name + "-n",
          children: [{ title: item.name, value: item.id }],
        });
      }
    }

    // 操作权限
    for (const item of actionsData) {
      const group = arr2.find((it) => it.title === item.group_name);
      if (group) {
        group.children.push({ title: item.name, value: item.id });
      } else {
        arr2.push({
          title: item.group_name,
          value: item.group_name + "-n",
          children: [{ title: item.name, value: item.id }],
        });
      }
    }

    permissions.value = arr;
    actions.value = arr2;
    init.value = false;
  });
};

// 提交表单
const submitForm = () => {
  formRef.value.validate().then(() => {
    if (loading.value) return;
    if (
      formState.value.permission_ids.length === 0 &&
      formState.value.action_ids.length === 0
    ) {
      message.error("必须选择至少一个权限！");
      return;
    }
    loading.value = true;
    const params = [
      ...formState.value.action_ids,
      ...formState.value.permission_ids,
    ];
    adminRole
      .storeAdminRole(formState.value.name, params)
      .then(() => {
        message.success("保存成功！");
        loading.value = false;
        props.onCancel();
      })
      .catch(() => {
        loading.value = false;
      });
  });
};
</script>
